package com.aisile.crowd_funding.system.controller;

import com.aisile.crowd_funding.common.controller.BaseController;
import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.common.utils.R;
import com.aisile.crowd_funding.common.utils.StringUtils;
import com.aisile.crowd_funding.system.mapper.SysUserMapper;
import com.aisile.crowd_funding.system.pojo.SysUser;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;


import java.util.List;

/**
 * @标题 LoginController
 * @作者 Mr.chen
 * @创建日期 2018/12/4 16:43
 * @版本号 1.0
 **/
@Controller
public class LoginController extends BaseController {
    @Autowired
    SysUserMapper sysUserMapper;

    @RequestMapping(value = {"/",""})
    public String defaultPage(){
        return "redirect:index";
    }
    @RequestMapping("login")
    public String login(){
        List<SysUser> sysUsers = sysUserMapper.selectByExample(null);
        System.out.println(sysUsers);
        return "login";
    }
   /**
    * 跳转首页方法
    * */

    @RequestMapping("index")
    public String index(Model model){
        model.addAttribute("username",getLoginUserName());
        return "index";
    }

    @RequestMapping("loginSign")
    @ResponseBody
    public R loginSign(String username,String password){
        //校验参数
        if(StringUtils.isBlank(username)){

            return R.error("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){

            return R.error("密码不能为空");
        }
        //  认证

        Subject subject= SecurityUtils.getSubject();
        //登陆认证
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, MD5Utils.encrypt(password));

        try {
            subject.login(usernamePasswordToken);
        }catch(UnknownAccountException e){

            R.error("未查询到该用户");

        }catch (LockedAccountException e){
            R.error("用户认证失败");
        }catch (AuthenticationException e){
            R.error("登录失败");
        }catch (Exception e){
            R.error("登录失败");
        }
        return R.ok();
    }

    @RequestMapping("main")
    public String main(){

        return "main";
    }
}
